package com.ror.java.se.array;

import java.util.Arrays;

public class Demo04BubbleSort {
    static boolean doBreak = true;

    public static void main(String[] args) {
        int[] arr = {2, 43, -13, 47, 5, 6, 7, 8};
        System.out.print("Before:");
        System.out.println(Arrays.toString(arr));
        bubbleSort(arr);
        System.out.print("After:");
        System.out.println(Arrays.toString(arr));
    }

    public static void bubbleSort(int[] arr) {
        int compareCnt = 0;
        for (int i = 0; i < arr.length; i++) {
            boolean didSwap = false; // 是否交换过
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                    didSwap = true;
                }
                compareCnt++;
            }
            // 一轮都没交换过，说明全都有序
            if (doBreak && !didSwap) {
                break;
            }
        }
        System.out.println("退出循环，执行了 " + compareCnt + " 次比较。");
    }
}
